/*
 *                          许可协议    
 *    
 *  COPYRIGHT ©2009 The Siox software project Lab.
 * 
 * 版权声明:                               
 *  1.任何"派生软件"都必须包含此许可协议,"派生软件的开发者"必   
 *  须完全保留被继承"软件"的许可协议和"版权信息".          
 *  2."派生软件开发者"在别人使用他所"派生"的"软件"时,自动成为"开
 *  发者".                               
 *  3."使用者"所生成的二进制代码文件须包含"原始开发者"的版权信息. 
 *  4.如该软件并未得到"开发者"的开源，那么"使用者"对本程序仅有使  
 *  用权，并不得进行反向工程.                      
 *  5.本协议保留"原始开发者"的版权信息在许可协议文本之内.
 *  6.本文档作为源代码/程序的基本协议,如有变化作为本协议扩充 
 *                                     
 * 免责声明:                               
 *  1.使用本"软件"都意味"使用者"是自愿使用本"软件",接受此许可协 
 *  议的所有条款.如果"使用者"不同意此许可协议就不能使用本"软件".  
 *  2.本"软件"虽然在开发者的开发环境下经过严格测试,但不能排除    
 *  "软件"中仍然存在错误.由于使用本"软件"所造成的任何损失,"开发  
 *  者"不负任何责任!                          
 *  3.本"软件"在被"使用"过程中,由"使用者"发现的任何错误必须再反 
 *  馈给"开发者"并经过"开发者"同意后,才可对其他人公开.任何未经过  
 *  "开发者"同意而被使用者擅自公开的本"软件"的错误,"开发者"有权  
 *  要求其对"开发者"名誉损失负法律责任. 
 * 
 *  个人主页:http://hi.baidu.com/lindily
 *  电子信箱:lindily@126.com               
 */
package cn.siox.util.database;

import com.db4o.*;
import com.db4o.query.Query;
import cn.siox.util.MD5;
import cn.siox.util.CurrentDateTime;

/**
 * @类名 UserOperater
 * @作者 Lindily
 * @日期 2009-6-19 2:47:56
 */
public class UserOperator {

    ObjectContainer userDB = Db4o.openFile("./data/" + "user" + ".db");
    UserDDL user = new UserDDL();

    public boolean[] loginUsr(String usr, String password) {
        boolean[] pass = new boolean[2];
        Query usrquery = userDB.query();
        usrquery.constrain(UserDDL.class);
        usrquery.descend("user").constrain(usr);
        ObjectSet usrResult = usrquery.execute();  //执行查询
        System.out.println("result size: " + usrResult.size());
        System.out.println("--------------------");
        while (usrResult.hasNext()) {
            user = (UserDDL) usrResult.next();
            if (user.getUser().equals(usr)) {
                pass[0] = true;
            } else {
                pass[0] = false;
            }
            MD5 md5 = new MD5(password);
            String postString = md5.compute();
//            System.out.println(postString);//调试后删除
            //添加数据库存储代码
            if (user.getPassword().equals(postString)) {
                pass[1] = true;
            } else {
                pass[1] = false;
            }
        }

        userDB.close();
        return pass;
    }

    /**
     *
     * @param usr
     * @param password
     * @param right
     * @return
     */
    public boolean registUsr(String usr, String password, boolean right) {
        boolean pass = false;//error!
        Query usrquery = userDB.query();
        usrquery.constrain(UserDDL.class);
        usrquery.descend("user").constrain(usr);
        ObjectSet usrResult = usrquery.execute();  //执行查询
        System.out.println("usrResult.size()------>"+usrResult.size());
        if (0 == usrResult.size()) {
            if (usr.equals("root")) {
                user.setId(0);
                user.setUser("root");
                user.setPassword(new MD5(password).compute());
                user.setRight(0);
                user.setRegistDate(new CurrentDateTime().getMediumDate());
                userDB.store(user);
                pass = true;
            } else {
                Query query = userDB.query();
                query.constrain(UserDDL.class);
                query.descend("id").constraints();
                ObjectSet result = query.execute();
                int id = result.size();
                System.out.println("all id="+id);
                user.setId(++id);//id
                user.setUser(usr);//user
                user.setPassword(new MD5(password).compute());//password
                user.setRegistDate(new CurrentDateTime().getMediumDate());//regist time
                if (!right) {
                    //common user right
                    user.setRight(2);
                } else {
                    //admin less root right
                    user.setRight(1);
                }
                pass = true;
                userDB.store(user);
            }

        } else {
            pass = false;
        }
        userDB.commit();
        userDB.close();
        return pass;
    }

    public boolean updateUsr(String usr,String pssword){
        Query usrquery = userDB.query();
        usrquery.constrain(UserDDL.class);
        usrquery.descend("user").constrain(usr);
        ObjectSet usrResult = usrquery.execute();
        while(usrResult.hasNext()){
            user = (UserDDL) usrResult.next();
            user.setPassword(pssword);
            userDB.store(user);
        }
        userDB.commit();
        return true;
    }

    public boolean deleteUsr(String usr, String password) {
        boolean rs = false;
        Query usrquery = userDB.query();
        usrquery.constrain(UserDDL.class);
        usrquery.descend("user").constrain(usr);
        ObjectSet usrResult = usrquery.execute();
        while (usrResult.hasNext()) {
            user = (UserDDL) usrResult.next();
            if (user.getPassword().equals(new MD5(password).compute())) {
                userDB.delete(user);
                rs = true;
            } else {
                rs = false;
                break;
            }
        }
        userDB.commit();
        userDB.close();
        return rs;
    }

    public boolean deleteUsr(int id, String password) {
        boolean rs = false;
        Query usrquery = userDB.query();
        usrquery.constrain(UserDDL.class);
        usrquery.descend("id").constrain(id);
        ObjectSet usrResult = usrquery.execute();
        while (usrResult.hasNext()) {
            user = (UserDDL) usrResult.next();
            if (user.getPassword().equals(new MD5(password).compute())) {
                userDB.delete(user);
                rs = true;
            } else {
                rs = false;
                break;
            }
        }
        userDB.commit();
        userDB.close();
        return rs;
    }

    private void deleteAll() {
        Query usrquery = userDB.query();
        usrquery.constrain(UserDDL.class);
        usrquery.descend("id").constraints();
        ObjectSet usrResult = usrquery.execute();
        while (usrResult.hasNext()) {
            user = (UserDDL) usrResult.next();
            userDB.delete(user);
        }
        userDB.close();
    }

    private void showUsr() {
        try {
            Query usrquery = userDB.query();
            usrquery.constrain(UserDDL.class);
            usrquery.descend("id").constraints();
            ObjectSet usrResult = usrquery.execute();
            System.out.println("usrResult size=" + usrResult.size());
            System.out.println("--------------------------------------");
            while (usrResult.hasNext()) {
                user = (UserDDL) (usrResult.next());
                System.out.println("id=" + user.getId());
                System.out.println("user=" + user.getUser());
                System.out.println("password=" + user.getPassword());
                System.out.println("right=" + user.getRight());
                System.out.println("regist date=" + user.getRegistDate());
                System.out.println("--------------------------------------");
            }
            userDB.commit();
        } catch (Exception e) {
        } finally {
            userDB.close();
        }
    }

    public static void main(String[] args) {
         //注意：一个数据库文件只能打开一个实例，如果要很多人操作该数据库，可以采用C/S 模式
        UserOperator uop = new UserOperator();
        boolean count;
//        uop.deleteAll();
//        uop.showUsr();
//        count = uop.registUsr("root", "123456", true);
//        System.out.println(count);
//        uop.showUsr();
//        count = uop.registUsr("aaa", "123", true);
//        System.out.println(count);
//        uop.showUsr();
//        count = uop.registUsr("bbb", "456", false);
//        System.out.println(count);
//        count = uop.registUsr("sfsfsf", "789", false);
//        System.out.println(count);
//        count = uop.registUsr("ksfdls", "789", false);
//        System.out.println(count);
//        uop.showUsr();
    }
}
